<?php
/**
 * Created by PhpStorm.
 * User: admin
 * Date: 2019-03-20
 * Time: 01:43
 */

namespace App\Sockets;


use Exception;
use models\User;
use BeReborn\Core\JSON;
use Swoole\Http\Request;
use Swoole\Http\Response;
use BeReborn\Web\Controller;
use Swoole\WebSocket\Server;

/**
 * Class GameSocket
 * @package app\websocket
 *
 * ota/tto data:
 *
 */
class WebSocketController extends Controller
{

	/**
	 * @param $fd
	 * @param Server $server
	 * @throws Exception
	 */
	public function onMessage($fd, $server)
	{
		$server->push($fd, 'ok');
		$result = router()->findByRoute();
		if ($result === null) {
			return;
		}
		if (!is_string($result)) {
			$result = JSON::encode($result);
		}
		$server->push($fd, $result);
	}

	/**
	 * @param Request $request
	 * @param Response $response
	 * @Event(handshake)
	 * @return bool
	 * @throws Exception
	 */
	public function onHandshake(Request $request, Response $response)
	{
		try {
			if (isset($request->get['debug']) && $request->get['debug'] == 'test') {
				return $this->connect($response);
			}

			if (!isset($request->get['auth'])) {
				return $this->disconnect($response, '暂无访问权限！', 400);
			}

			$params = $this->onDecode($request->get['auth']);
			if (!(($user = User::findOne(Auth()->checkAuth($params))) instanceof User)) {
				return $this->disconnect($response, '授权凭证或已过期！', 401);
			}

			return $this->connect($response);
		} catch (Exception $exception) {
			$message = $exception->getFile() . ':' . $exception->getMessage();
			$this->error($message);
			return $this->disconnect($response, $message, $exception->getCode());
		}
	}


	/**
	 * @param Response $response
	 * @param $message
	 * @param $code
	 * @return mixed
	 */
	public function disconnect($response, $message, $code)
	{
		if ($code === 101) {
			$code = 402;
		}
		$response->status($code);
		$response->end($message);
		return false;
	}


	/**
	 * @param Response $response
	 * @return mixed
	 */
	public function connect($response)
	{
		$response->status(101);
		$response->end();
		return true;
	}

	/**
	 * @param $auth
	 * @return mixed
	 * @throws
	 */
	private function onDecode($auth)
	{
		$decode = base64_decode($auth);
		parse_str($decode, $params);

		if (!isset($params['refresh']) || !isset($params['token'])) {
			throw new Exception('暂无访问权限', 402);
		}
		return $params;
	}
}
